# -*- coding: utf-8 -*-            
# @Author : chenliang
# @Time : 2025/3/31 18:38

import pytest
import subprocess
import os
from pathlib import Path
from collections import defaultdict  # 新增导入
from Case.python_ui.Common.dingtalk import Ding


# ---------- 基础配置（修改此处路径） ----------
# mac
# TEST_CASE_DIR = "../Test_case/test_consignor_carpool.py"  # 测试用例路径
# ALLURE_RESULT_DIR = "../report/result"
# ALLURE_REPORT_DIR = "../report/report_html"
# windows
TEST_CASE_DIR = r"..\Test_case\test_consignor_carpool.py"  # 测试用例路径
ALLURE_RESULT_DIR = r"..\report\result"
ALLURE_REPORT_DIR = r"..\report\report_html"

MARKER_EXPRESSION = "login"  # pytest 标记筛选
THREAD_NUM = 1  # 并行线程数


# ---------- 统计结果收集器 ----------
class ResultCollector:
    def __init__(self):
        self.total = 0
        self.passed = 0
        self.failed = 0
        self.file_stats = defaultdict(lambda: {  # 新增：按文件分类统计
            "total": 0,
            "passed": 0,
            "failed": 0
        })

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_makereport(self, item):
        outcome = yield
        report = outcome.get_result()
        if report.when == "call":
            # 提取测试用例所属的文件路径
            file_path = os.path.normpath(report.nodeid.split("::")[0])  # 关键：解析 nodeid

            # 更新全局统计
            self.total += 1
            if report.passed:
                self.passed += 1
            elif report.failed:
                self.failed += 1

            # 更新文件级统计
            self.file_stats[file_path]["total"] += 1
            if report.passed:
                self.file_stats[file_path]["passed"] += 1
            elif report.failed:
                self.file_stats[file_path]["failed"] += 1

    # ---------- 主执行流程 ----------
if __name__ == "__main__":
    collector = ResultCollector()
    pytest_args = [
            "-v", "-m", MARKER_EXPRESSION,
            "--alluredir", ALLURE_RESULT_DIR,
            TEST_CASE_DIR
        ]
    exit_code = pytest.main(pytest_args, plugins=[collector])

    # # 打印全局统计
    # print("\n" + "=" * 40)
    # print(f"[全局统计] 总用例数: {collector.total}, 成功: {collector.passed}, 失败: {collector.failed}")
    # print("=" * 40 + "\n")


    dict_report = {}
    # 打印按文件统计的明细
    print("[文件级统计]")
    for file_path, stats in collector.file_stats.items():
        dict_report[file_path] = f"总用例数: {stats['total']}, 成功: {stats['passed']}, 失败: {stats['failed']}"
        print(f"文件: {file_path}")
        print(f"  └─ 总用例数: {stats['total']}, 成功: {stats['passed']}, 失败: {stats['failed']}")
    print("\n")


    # 生成 Allure 报告
    if Path(ALLURE_RESULT_DIR).exists():
        cmd = [
            # "allure",
            r"C:\Users\Administrator\Downloads\allure-2.33.0\allure-2.33.0\bin\allure.bat",
            "generate",
            ALLURE_RESULT_DIR,
            "-o", ALLURE_REPORT_DIR,
            "--clean"
        ]
        try:
            subprocess.run(cmd, check=True)
            print(f"Allure 报告已生成至：{os.path.abspath(ALLURE_REPORT_DIR)}")
        except Exception as e:
            print(f"生成 Allure 报告失败: {str(e)}")
            print(f"Allure 报告已生成至：{os.path.abspath(ALLURE_REPORT_DIR)}")
    else:
        print(f"警告：Allure 结果目录不存在 {ALLURE_RESULT_DIR}")

    result = Ding().report_message(report=dict_report, phone='17625890895')
    Ding().send_to_dingtalk(
     'https://oapi.dingtalk.com/robot/send?access_token=69084d85fde044caf8b3e12128779646cf1552d0606208923186cfabb275e211',
        result)

    print(result)


    # 根据失败数返回退出码（用于 CI/CD）
    exit(1 if collector.failed > 0 else 0)




